﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    /**
     * 多线程
     * url: https://www.cnblogs.com/Brambling/p/7144015.html
     * 2019-8-15
     */
    class Program
    {
        static void Main(string[] args)
        {

            ThreadDemoClass threadDemoClass = new ThreadDemoClass();


            //设置当没有请求时线程维护的空闲线程数
            //第一个参数为辅助线程数
            //第二个参数为异步I/O线程数
            ThreadPool.SetMinThreads(5, 5);


            //设置同时处于活动状态的线程池的线程数，大于此数的线程保持排队状态
            //第一个参数为辅助线程数
            //第二个参数为异步I/O线程数
            ThreadPool.SetMaxThreads(100, 100);

            //10101
            ParameterizedThreadStart parameterizedThreadStart = new ParameterizedThreadStart(threadDemoClass.Run);

            //创建一个新线程 10102
            //Thread thread = new Thread(threadDemoClass.Run);
            //10101
            Thread thread = new Thread(parameterizedThreadStart);

            
            thread.IsBackground = true; //后台线程

            thread.Name = "T" + DateTime.Now.Ticks.ToString();
            thread.Priority = ThreadPriority.Highest; //设置为最高优先级
                                                      /**
                                                       * 没有设置优先级的时候 先输出101,102; 然后201,202
                                                       * 设置为最高级优先级的时候             
                                                       */

            UserInfo userInfo = new UserInfo()
            {
                Name = "Tom Json",
                Age = 28
            };


            //开始线程，并传入参数 10101
            thread.Start(userInfo);

            //等待直到本线程完成再进行主线程
            thread.Join(); //可以指定阻塞线程的时间，如果时间内线程没有终止就返回false,否则就返回true

            Thread.Sleep(1000); //休眠1S 再继续执行下面的


            // 创建新线程的方式2
            //ThreadStart threadStart = new ThreadStart(threadDemoClass.Run);
            //Thread thread1 = new Thread(threadStart);
            //thread1.Start();

            Console.WriteLine("101 Main thread working..."+DateTime.Now.ToString());
            Console.WriteLine("102 Main Thread ID:" + Thread.CurrentThread.ManagedThreadId);
            


            Console.ReadKey();
        }
    }


    public class ThreadDemoClass
    {
        public void Run(object obj)
        {
            UserInfo info = obj as UserInfo;
            Console.WriteLine("My name is " + info.Name+",I am "+info.Age);
            Console.WriteLine("201 Child thread working..."+DateTime.Now.ToString());
            Console.WriteLine("202 Child thread id:"+Thread.CurrentThread.ManagedThreadId);
        }
    }


    public class UserInfo
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
